package org.hfy.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.hfy.common.ApiResponse;
import org.hfy.dto.warehouse.InboundCreateDTO;
import org.hfy.dto.warehouse.InboundQueryDTO;
import org.hfy.dto.warehouse.InventoryAdjustmentDTO;
import org.hfy.dto.warehouse.InventoryQueryDTO;
import org.hfy.dto.warehouse.OutboundCreateDTO;
import org.hfy.dto.warehouse.OutsourcingInboundCreateDTO;
import org.hfy.entity.Inbound;
import org.hfy.entity.Inventory;
import org.hfy.entity.Outbound;
import org.hfy.entity.QuotationItem;
import org.hfy.service.InboundService;
import org.hfy.service.InventoryService;
import org.hfy.service.OutboundService;
import org.hfy.service.OutboundDeliveryService;

/**
 * 仓库管理控制器
 * 
 * @author hfy
 * @version 1.0
 */
@RestController
@RequestMapping("/warehouse")
public class WarehouseController {

    @Autowired
    private InboundService inboundService;

    @Autowired
    private OutboundService outboundService;

    @Autowired
    private InventoryService inventoryService;

    @Autowired
    private OutboundDeliveryService outboundDeliveryService;

    // ==================== 入库管理 ====================

    /**
     * 获取可入库的订单列表
     */
    @GetMapping("/inbound/available-orders")
    public ApiResponse<IPage<QuotationItem>> getAvailableOrders(InboundQueryDTO queryDTO) {
        IPage<QuotationItem> result = inboundService.getAvailableOrdersPage(queryDTO);
        return ApiResponse.success(result);
    }

    /**
     * 创建入库单
     */
    @PostMapping("/inbound")
    public ApiResponse<Inbound> createInbound(@Validated @RequestBody InboundCreateDTO createDTO) {
        Inbound inbound = inboundService.createInbound(createDTO);
        return ApiResponse.success(inbound);
    }

    /**
     * 获取入库记录列表
     */
    @GetMapping("/inbound/records")
    public ApiResponse<IPage<Inbound>> getInboundRecords(InboundQueryDTO queryDTO) {
        IPage<Inbound> result = inboundService.getInboundRecordsPage(queryDTO);
        return ApiResponse.success(result);
    }

    /**
     * 获取入库单详情
     */
    @GetMapping("/inbound/{id}")
    public ApiResponse<Inbound> getInboundById(@PathVariable Long id) {
        Inbound inbound = inboundService.getById(id);
        if (inbound == null) {
            return ApiResponse.error("入库单不存在");
        }
        return ApiResponse.success(inbound);
    }

    /**
     * 删除入库单
     */
    @DeleteMapping("/inbound/{id}")
    public ApiResponse<Void> deleteInbound(@PathVariable Long id) {
        boolean success = inboundService.removeById(id);
        if (success) {
            return ApiResponse.success();
        } else {
            return ApiResponse.error("删除失败");
        }
    }

    /**
     * 基于外发单创建入库单
     */
    @PostMapping("/inbound/outsourcing")
    public ApiResponse<Inbound> createOutsourcingInbound(@Validated @RequestBody OutsourcingInboundCreateDTO createDTO) {
        Inbound inbound = inboundService.createOutsourcingInbound(createDTO);
        return ApiResponse.success(inbound);
    }

    /**
     * 获取外发单已入库总数量
     */
    @GetMapping("/inbound/outsourcing/{outsourcingId}/total-quantity")
    public ApiResponse<Integer> getTotalInboundQuantityByOutsourcing(@PathVariable Long outsourcingId) {
        Integer totalQuantity = inboundService.getTotalInboundQuantityByOutsourcingId(outsourcingId);
        return ApiResponse.success(totalQuantity != null ? totalQuantity : 0);
    }

    // ==================== 出库管理 ====================

    /**
     * 获取可出库的库存列表
     */
    @GetMapping("/outbound/available-stock")
    public ApiResponse<IPage<Inventory>> getAvailableStock(InboundQueryDTO queryDTO) {
        IPage<Inventory> result = outboundService.getAvailableStockPage(queryDTO);
        return ApiResponse.success(result);
    }

    /**
     * 创建出库单
     */
    @PostMapping("/outbound")
    public ApiResponse<Outbound> createOutbound(@Validated @RequestBody OutboundCreateDTO createDTO) {
        Outbound outbound = outboundService.createOutbound(createDTO);
        return ApiResponse.success(outbound);
    }

    /**
     * 获取出库记录列表
     */
    @GetMapping("/outbound/records")
    public ApiResponse<IPage<Outbound>> getOutboundRecords(InboundQueryDTO queryDTO) {
        IPage<Outbound> result = outboundService.getOutboundRecordsPage(queryDTO);
        return ApiResponse.success(result);
    }

    /**
     * 获取出库单详情
     */
    @GetMapping("/outbound/{id}")
    public ApiResponse<Outbound> getOutboundById(@PathVariable Long id) {
        Outbound outbound = outboundService.getById(id);
        if (outbound == null) {
            return ApiResponse.error("出库单不存在");
        }
        return ApiResponse.success(outbound);
    }

    /**
     * 删除出库单
     */
    @DeleteMapping("/outbound/{id}")
    public ApiResponse<Void> deleteOutbound(@PathVariable Long id) {
        boolean success = outboundService.removeById(id);
        if (success) {
            return ApiResponse.success();
        } else {
            return ApiResponse.error("删除失败");
        }
    }

    /**
     * 打印送货单
     */
    @GetMapping("/outbound/{id}/delivery-note")
    public ResponseEntity<byte[]> printDeliveryNote(@PathVariable Long id) {
        try {
            // 获取出库单信息
            Outbound outbound = outboundService.getById(id);
            if (outbound == null) {
                return ResponseEntity.notFound().build();
            }

            // 生成送货单PDF
            byte[] pdfBytes = outboundDeliveryService.generateDeliveryNotePdf(outbound);
            
            // 设置响应头
            String fileName = "送货单_" + outbound.getOutboundNo() + ".pdf";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_PDF);
            headers.setContentDispositionFormData("attachment", fileName);
            headers.setContentLength(pdfBytes.length);
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(pdfBytes);
                    
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 预览送货单HTML
     */
    @GetMapping("/outbound/{id}/delivery-preview")
    public ResponseEntity<String> previewDeliveryNote(@PathVariable Long id) {
        try {
            // 获取出库单信息
            Outbound outbound = outboundService.getById(id);
            if (outbound == null) {
                return ResponseEntity.notFound().build();
            }

            // 生成送货单HTML内容
            String htmlContent = outboundDeliveryService.generateDeliveryNoteHtml(outbound);
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.TEXT_HTML);
            headers.add("Content-Type", "text/html; charset=UTF-8");
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(htmlContent);
                    
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    // ==================== 库存管理 ====================

    /**
     * 获取库存列表
     */
    @GetMapping("/inventory")
    public ApiResponse<IPage<Inventory>> getInventory(InventoryQueryDTO queryDTO) {
        IPage<Inventory> result = inventoryService.getInventoryPage(queryDTO);
        return ApiResponse.success(result);
    }

    /**
     * 根据厂内编号获取库存详情
     */
    @GetMapping("/inventory/{factoryNo}")
    public ApiResponse<Inventory> getInventoryByFactoryNo(@PathVariable String factoryNo) {
        Inventory inventory = inventoryService.getByFactoryNo(factoryNo);
        if (inventory == null) {
            return ApiResponse.error("库存记录不存在");
        }
        return ApiResponse.success(inventory);
    }

    /**
     * 库存调整
     */
    @PutMapping("/inventory/{id}/adjustment")
    public ApiResponse<Inventory> adjustInventory(@PathVariable Long id, 
                                                  @Validated @RequestBody InventoryAdjustmentDTO adjustmentDTO) {
        Inventory inventory = inventoryService.adjustInventory(id, adjustmentDTO);
        return ApiResponse.success(inventory);
    }

    /**
     * 获取低库存预警列表
     */
    @GetMapping("/inventory/low-stock")
    public ApiResponse<Object> getLowStockItems() {
        return ApiResponse.success(inventoryService.getLowStockItems());
    }

    // ==================== 工具API ====================

    /**
     * 生成厂内编号
     */
    @GetMapping("/generate-factory-no")
    public ApiResponse<String> generateFactoryNo() {
        String factoryNo = inboundService.generateFactoryNo();
        return ApiResponse.success(factoryNo);
    }

    /**
     * 根据报价明细ID获取已入库总数
     */
    @GetMapping("/inbound/total-quantity/{quotationItemId}")
    public ApiResponse<Integer> getTotalInboundQuantity(@PathVariable Long quotationItemId) {
        Integer total = inboundService.getTotalInboundQuantityByQuotationItemId(quotationItemId);
        return ApiResponse.success(total);
    }

    /**
     * 根据入库单ID获取已出库总数
     */
    @GetMapping("/outbound/total-quantity/{inboundId}")
    public ApiResponse<Integer> getTotalOutboundQuantity(@PathVariable Long inboundId) {
        Integer total = outboundService.getTotalOutboundQuantityByInboundId(inboundId);
        return ApiResponse.success(total);
    }
} 